package org.jeecg.modules.website.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.website.entity.JcChannel;
import org.jeecg.modules.website.mapper.JcChannelMapper;
import org.jeecg.modules.website.service.IJcChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description: jc_channel
 * @Author: jeecg-boot
 * @Date:   2020-06-21
 * @Version: V1.0
 */
@Service
public class JcChannelServiceImpl extends ServiceImpl<JcChannelMapper, JcChannel> implements IJcChannelService {
@Autowired
JcChannelMapper channelMapper;

    @Override
    public  List<JcChannel> getChannelListByParentCode(String parentCode) {
        List<JcChannel> channels= channelMapper.getChannelListByParentCode(parentCode);
       // IPage<JcChannel> page=new Ipage ;
        return channels;
    }

    @Override
    public List<JcChannel> getParentChannelByCode(String channelCode) {
//        channelCode="SELECT T2.* FROM ( SELECT @r AS _id, (SELECT @r := parentid FROM `jc_channel` WHERE id = _id) AS parentid, \n" +
//                "        @l := @l + 1 AS lvl FROM (SELECT @r := '"+channelCode+"', @l := 0) vars, jc_channel h WHERE @r <> 0) T1 \n" +
//                "JOIN jc_channel T2 ON T1._id = T2.id AND T2.`parentid` != '0'  ORDER BY T1.lvl DESC ";
        List<JcChannel> jcChannels=new ArrayList<>();
        getChannelParentListById(channelCode,jcChannels);
        Collections.reverse(jcChannels);
        return jcChannels;
    }

    private List<JcChannel> getChannelParentListById(String id, List<JcChannel> jcChannels){
        QueryWrapper<JcChannel> jcChannelQueryWrapper=new QueryWrapper<>();
        jcChannelQueryWrapper.eq("id",id);
        JcChannel jcChannel=channelMapper.selectOne(jcChannelQueryWrapper);
        if(jcChannel!=null && !"0".equals(jcChannel.getParentid())){
            jcChannels.add(jcChannel);
            getChannelParentListById(jcChannel.getParentid(), jcChannels);
        }
        return jcChannels;
    }
}
